package com.lss.cloud.service.impl;

import com.lss.cloud.apis.AccountFeignApi;
import com.lss.cloud.apis.StorageFeignApi;
import com.lss.cloud.entities.Order;
import com.lss.cloud.mapper.OrderMapper;
import com.lss.cloud.service.OrderService;
import io.seata.core.context.RootContext;
import io.seata.spring.annotation.GlobalTransactional;
import jakarta.annotation.Resource;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import tk.mybatis.mapper.entity.Example;

import javax.persistence.Lob;

@Slf4j
@Service
public class OrderServiceImpl implements OrderService {
    @Resource
    private OrderMapper orderMapper;
    @Resource//订单微服务通过OpenFeign去调用库存微服务
    private StorageFeignApi storageFeignApi;
    @Resource//订单微服务通过OpenFeign去调用账户微服务
    private AccountFeignApi accountFeignApi;


    @Override
  //  @GlobalTransactional(name = "zzyy-create-order", rollbackFor = Exception.class) //AT
    //@GlobalTransactional @Transactional(rollbackFor = Exception.class) //XA
    public void create(Order order) {
        //获得 xid
        String xid = RootContext.getXID();
        order.setStatus(0);
        log.info("---------------》xid：" + xid);
        int res = orderMapper.insertSelective(order);

        Order orderFromDB = null;
        if (res > 0) {   //1.从数据库中进行查询
            orderFromDB = orderMapper.selectOne(order);
            log.info("--------------->order: " + orderFromDB);
            System.out.println();
            // 2. 修改库存
            log.info("--------------->修改库存");
            storageFeignApi.decrease(orderFromDB.getProductId(), orderFromDB.getCount());
            System.out.println();
            // 3 修改account
            log.info("--------------->修改金额");
            accountFeignApi.decrease(orderFromDB.getUserId(), orderFromDB.getMoney());
            System.out.println();
            // 4 修改订单状态
            log.info("---------------->修改订单状态");
            orderFromDB.setStatus(1);
            //int i = orderMapper.insertSelective(orderFromDB);
            Example whereCondition = new Example(Order.class);
            Example.Criteria criteria = whereCondition.createCriteria();
            criteria.andEqualTo("userId",orderFromDB.getUserId());
            criteria.andEqualTo("status",0);
            int i = orderMapper.updateByExampleSelective(orderFromDB, whereCondition);
        }
        System.out.println();
        log.info("---------------》xid：" + xid);


    }
}